package org.eden.karb.common.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Utility to get a deployed Spring bean.
 *
 * @author trsimoes
 * @version $Revision:$
 */
public class BeanHelper {
    /**
     * Application Context.
     */
    private static final ThreadLocal<ApplicationContext> context = new ThreadLocal<ApplicationContext>();

    /**
     * Constructs a new <code>BeanHelper</code>.
     *
     */
    private BeanHelper() {
        // Default constructor
    }

    /**
     * Returns the Bean according to the required Bean Identifier.
     *
     * @param beanID Bean Identifier
     * @param <T> The bean type object
     * @return Resulting Bean
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(final String beanID) {
        T result = null;

        try {
            result = (T) getApplicationContext().getBean(beanID);
        } catch (final BeansException e) {
            System.err.println("error getting bean " + beanID + "\n" + e);
        }

        return result;
    }

    /**
     * Returns this WebApplication Context.
     *
     * @return Current Application Context.
     */
    private static ApplicationContext getApplicationContext() {
        ApplicationContext applicationContext = context.get();

        if (applicationContext == null) {
            applicationContext = new ClassPathXmlApplicationContext("spring/application-configuration.xml");
            context.set(applicationContext);
        }

        return applicationContext;
    }
}
